package com.zzj.ecology.framework.manager.async;

import com.zzj.ecology.common.constant.Constant;
import com.zzj.ecology.common.constant.LogConstants;
import com.zzj.ecology.common.utils.*;
import com.zzj.ecology.framework.utils.LogUtils;
import com.zzj.ecology.system.bean.minitor.SysLoginInfor;
import com.zzj.ecology.system.bean.minitor.SysOperLog;
import com.zzj.ecology.system.bean.minitor.SysUserOnline;
import com.zzj.ecology.system.service.minitor.SysLoginInforService;
import com.zzj.ecology.system.service.minitor.SysOperLogService;
import com.zzj.ecology.system.service.minitor.SysUserOnlineService;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.TimerTask;

/**
 * 异步工厂
 */
@Component
public class AsyncTaskFactory {

    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    @Autowired
    private SysOperLogService sysOperLogService;

    @Autowired
    private SysLoginInforService sysLoginInforService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SysUserOnlineService sysUserOnlineService;



    /**
     * 操作日志记录
     *
     * @param sysOperLog
     * @return
     */
    public TimerTask recordOper(final SysOperLog sysOperLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                sysOperLog.setOperLocation(AddressUtils.getRealAddressByIP(sysOperLog.getOperIp()));
                sysOperLogService.insert(sysOperLog);
            }
        };
    }

    /**
     *
     * @param username 登录用户
     * @param status  登录状态
     * @param message (国际化)登录信息
     * @param args
     * @return
     */
    public TimerTask recordLoginInfor(final String username, final String status, final Date loginTime, final String message, final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIPAddress(request);
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();

                SysLoginInfor loginInfor = new SysLoginInfor();
                loginInfor.setLoginName(username);
                loginInfor.setLoginTime(loginTime);
                loginInfor.setIpaddr(ip);
                loginInfor.setLoginLocation(address);
                loginInfor.setBrowser(browser);
                loginInfor.setOs(os);
                loginInfor.setMsg(message);
                // 状态
                if (StringUtils.equalsAny(status, Constant.LOGIN_SUCCESS, Constant.LOGOUT, Constant.REGISTER)) {
                    loginInfor.setStatus(LogConstants.LoginInforLog.STATUS_LOGIN_SUCCESS);
                } else if(StringUtils.equals(status, Constant.LOGIN_FAIL)){
                    loginInfor.setStatus(LogConstants.LoginInforLog.STATUS_LOGIN_FAILURE);
                }
                sysLoginInforService.insert(loginInfor);
            }
        };
        return timerTask;
    }

    public TimerTask recordOnline(final SysUserOnline userOnline) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();

                userOnline.setBrowser(browser);
                userOnline.setOs(os);
                userOnline.setStatus(LogConstants.OnlineLog.STATUS_ONLINE);
                sysUserOnlineService.insert(userOnline);
            }
        };
        return timerTask;
    }

    public TimerTask updateOnlineInfo(SysUserOnline sysUserOnline) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                try {
                    sysUserOnlineService.updateStatus(sysUserOnline);
                } catch (Exception e) {

                }
            }
        };
        return timerTask;
    }

}
